package com.action.app;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.Admin;
import com.pojo.Apk;
import com.service.ApkService;
import com.service.SshCopyFileService;
import com.util.ApkUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;

@RequestMapping("/apk")
@Controller
public class AppGuanliAction {

    @Autowired
    private ApkService apkService;
    @Autowired
    private SshCopyFileService sshCopyFileService;

    @Value("${upload.dir}")
    private String upload ;

    @Value("${upload.tmp.dir}")
    private String tmp;
    /**
     * 查询apk信息
     * /getApkListByElife
     * @return
     */
    @RequestMapping("/getApkList")
    @ResponseBody
    public ResponseBean getApkListByElife(String apkName, String carType, String carGs, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit){
        IPage iPage = apkService.getApkListByElife(page,limit,apkName,carType,carGs);
        return new ResponseBean(0,iPage.getTotal(),"查询成功",iPage.getRecords());
    }

    /**
     * 修改apk状态
     * @param id
     * @return
     */
    @RequestMapping("updApkStatus")
    @ResponseBody
    public ResponseBean updApkStatus(String id, String status){
        Apk apk = apkService.getById(id);
        apk.setStatus(Integer.valueOf(status));
        if(apkService.updateById(apk)){
            return new ResponseBean(0,1,"成功！","");
        }else {
            return new ResponseBean(1,1,"失败！","");
        }
    }

    /**
     * 保存应用
     * @param apk
     * @return
     */
    @RequestMapping("/saveApk")
    @ResponseBody
    public ResponseBean saveApk(@RequestBody Apk apk, HttpServletRequest request) {

        Apk saveApk = new Apk();
        saveApk.setApk_name(apk.getApk_name());
        saveApk.setApk_package(apk.getApk_package());
        saveApk.setMd5(apk.getMd5());
        saveApk.setPicture(apk.getPicture());
        saveApk.setVersions(apk.getVersions());
        saveApk.setFile_name(apk.getFile_name());
        saveApk.setStatus(apk.getStatus());
        saveApk.setPublicity(apk.getPublicity());
        saveApk.setCreateTime(new Date());
        saveApk.setTarget_url(apk.getTarget_url());
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if(null != admin){
            saveApk.setUser_id(admin.getId());
        }
        int m = apkService.countApk(apk.getVersions(),apk.getApk_name());
        if(m!=0){
            return new ResponseBean(1,1,"版本号已存在！",null);
        }else{
            int n = apkService.saveApk(saveApk);
            if (n != 1) {
                return new ResponseBean(2,1,"添加失败！",null);
            }
            FileUtil.copy(tmp + apk.getPicture(), upload, true) ;
//            sshCopyFileService.copy(upload + apk.getPicture());
            //tmp复制图片到upload
//            String srcPathStr = tmp + apk.getPicture(); //源文件地址
//            String desPathStr = upload; //目标文件地址
//            CopyFile.copy(srcPathStr, desPathStr);
            return new ResponseBean(3,1,"添加成功！",null);
        }
    }

    /**
     * 修改应用
     * @param apk
     * @return
     */
    @RequestMapping("/updApk")
    @ResponseBody
    public ResponseBean updApk(@RequestBody Apk apk) {

//    System.out.println("apk名称："+apkName+"//图片："+picture+"//文件名："+fileName+"//版本号："+versions);
        Apk queryApk = apkService.getById(apk.getId());
        if(apkService.updateById(apk)){
            if(StringUtil.isNotNull(apk.getPicture()) && apk.getPicture().equals(queryApk.getPicture())==false){
                FileUtil.copy(tmp + apk.getPicture(), upload, true) ;
//                sshCopyFileService.copy(upload + apk.getPicture());
                //tmp复制图片到upload
//                String srcPathStr = tmp + apk.getPicture(); //源文件地址
//                String desPathStr = upload; //目标文件地址
//                CopyFile.copy(srcPathStr, desPathStr);
            }
            return new ResponseBean(3,1,"修改成功！",null);
        }
        return new ResponseBean(1,1,"修改失败！",null);
    }

    @RequestMapping(value = "/upLoadApk")
    @ResponseBody
    public ResponseBean upLoadApk(MultipartFile file, HttpServletRequest request) {
        String newFilename = null;
        String realPath = null;
        Apk file2 = new Apk();
        try {

            realPath =upload + "/addApk";
            if (new File(realPath).exists()==false) new File(realPath).mkdir();

            // 获取文件名
            String filename = file.getOriginalFilename();
            //System.out.println("文件名："+filename);

            // 获取文件后缀名
            String extensionname = filename.substring(filename.lastIndexOf(".") + 1);

            // 给上传的文件起别名，有很多种方式
            newFilename = String.valueOf(System.currentTimeMillis()) + "." + extensionname;

            // 创建File对象，传入目标路径参数，和新的文件别名
            File dir = new File(realPath, newFilename);
            //System.out.println("目标路径参数:"+realPath);

            if (!dir.exists()) {
                // 如果dir代表的文件不存在，则创建它，
                // dir.mkdirs();
            }

            // 如果存在则直接执行下面操作
            file.transferTo(dir);// 将上传的实体文件复制到指定目录upload下

            file2.setTarget_url("/addApk/" + newFilename);
            //System.out.println("文件名："+newFilename);

            //sshCopyFileService.copy(upload + file2.getFile_name());

            String s = realPath.replace("\\", "/");
            String s1 = s +"/"+ newFilename;
            //System.out.println(s1);

            Map<String, Object> mapApk = ApkUtil.readAPK(s1);
            String packageName = mapApk.get("pkgname").toString();
            String versionCode = mapApk.get("versioncode").toString();
            file2.setVersions(mapApk.get("versioncode").toString());
            file2.setApk_name(mapApk.get("filename").toString());
            file2.setFile_name(filename);
            file2.setApk_package(packageName);

            String md51 = DigestUtils.md5DigestAsHex(newFilename.getBytes());
            file2.setMd5(md51);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseBean(0,1,"成功", file2);
    }
    /**
     * apk下载
     * @return
     */
    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<InputStreamResource> download(String id, HttpServletResponse response){
        Apk apk = apkService.getById(id);
        return downLoadApk(response, apk);
    }

    private ResponseEntity<InputStreamResource> downLoadApk(HttpServletResponse response, Apk apk) {
        if (null != apk) {
            String locationUrl = apk.getTarget_url();
            String apkPath = upload + locationUrl;
            File file = new File(apkPath);
            String fileName = file.getName(); //下载的文件名
            // 如果文件名存在，则进行下载
            if (file.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    System.out.println("Download the song failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {//对应文件不存在
                try {
                    //设置响应的数据类型是html文本，并且告知浏览器，使用UTF-8 来编码。
                    response.setContentType("text/html;charset=UTF-8");

                    //String这个类里面， getBytes()方法使用的码表，是UTF-8，  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                    String csn = Charset.defaultCharset().name();

                    System.out.println("默认的String里面的getBytes方法使用的码表是： " + csn);

                    //1. 指定浏览器看这份数据使用的码表
                    response.setHeader("Content-Type", "text/html;charset=UTF-8");
                    OutputStream os = response.getOutputStream();

                    os.write("对应文件不存在".getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            try {
                //设置响应的数据类型是html文本，并且告知浏览器，使用UTF-8 来编码。
                response.setContentType("text/html;charset=UTF-8");

                //String这个类里面， getBytes()方法使用的码表，是UTF-8，  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                String csn = Charset.defaultCharset().name();

                System.out.println("默认的String里面的getBytes方法使用的码表是： " + csn);

                //1. 指定浏览器看这份数据使用的码表
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                OutputStream os = response.getOutputStream();

                os.write("应用不存在".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
